package com.wang.mvchain.outer.service.implay;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.Callable;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.service.BaseServiceImplay;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.ExecutorServiceUtil;
import com.wang.mvchain.common.util.PageInfoUtil;
import com.wang.mvchain.outer.IOutTimerService;
import com.wang.mvchain.outer.enums.TradeEnum;
import com.wang.mvchain.outer.service.ITradeService;
import com.wang.mvchain.outer.util.TradeUtil;
import com.wang.mvchain.system.pojo.ADept;
import com.wang.mvchain.system.pojo.ADeptEnum;
import com.wang.mvchain.system.pojo.ATradeType;
import com.wang.mvchain.system.pojo.ATradeTypeEnum;
import com.wang.mvchain.system.pojo.AWebsite;
import com.wang.mvchain.system.pojo.AWebsiteEnum;
import com.wang.mvchain.system.service.IWebsiteService;
import com.wang.mvchain.users.pojo.AUsers;
import com.wang.mvchain.users.pojo.AUsersAccount;
import com.wang.mvchain.users.pojo.AUsersAccountEnum;
import com.wang.mvchain.users.pojo.AUsersTask;
import com.wang.mvchain.users.pojo.AUsersTaskEnum;
import com.wang.mvchain.users.pojo.AUsersTaskOrder;
import com.wang.mvchain.users.pojo.AUsersTaskOrderEnum;
import com.wang.mvchain.users.service.IOrdersService;
import com.wang.mvchain.users.service.IUsersService;
import com.wang.mvchain.util.ServiceCallableUtil;

@Component("outTimerService")
public class OutTimerServiceImplay extends BaseServiceImplay implements
		IOutTimerService
{
	@Resource
	private IWebsiteService websiteService ; 
	@Resource
	private IUsersService usersService;
	@Resource
	private IOrdersService ordersService;
	
	@Override
	public void startDeptService()
	{
		// 抓取交易网站的最新数据
		ConstatFinalUtil.TIMER_LOG.info("----- 抓取交易网站开始 -----");
		List<Callable<Object>> callList = new ArrayList<Callable<Object>>();
		Map<String, Object> condMap = new HashMap<String, Object>();
		for (Iterator iterator = TradeUtil.tradeServiceMap.entrySet()
				.iterator(); iterator.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "";
			ITradeService tradeService = (ITradeService) me.getValue();
			// 按照id查询
			condMap.clear();
			condMap.put("id", tradeService.findWebsiteId() + "");
			AWebsite website = this.websiteService.findOneWebsiteService(condMap);
			if (website == null || website.getStatus() == AWebsiteEnum.STATUS_DISABLE.getStatus())
			{
				continue;
			}

			JSONObject moneyStautsJSON = website.getMoneyStatusJSON();
			for (Iterator iterator2 = moneyStautsJSON.entrySet().iterator(); iterator2
					.hasNext();)
			{
				Entry me2 = (Entry) iterator2.next();
				String key2 = me2.getKey() + "";
				JSONObject val2JSON = (JSONObject) me2.getValue();
				val2JSON.put("key", key);
				if ("1".equalsIgnoreCase(val2JSON.get("status") + "")
						&& !"".equalsIgnoreCase(val2JSON.get("name") + ""))
				{
					String name = val2JSON.get("name") + "";
					/* 查询交易对是否正常 */
					condMap.clear();
					condMap.put("name", name);
					ATradeType tradeType = this.websiteService.findOneTradeTypeService(condMap);
					if(tradeType.getStatus() == ATradeTypeEnum.STATUS_DISABLE.getStatus())
					{
						/* 如果交易对,禁用,就不再进行爬虫 */
						continue ; 
					}
					
					Map<String, Object> thrMap = new HashMap<String, Object>();
					thrMap.put("tradeService", tradeService);
					thrMap.put("val2JSON", val2JSON);
					
					ServiceCallableUtil multiThreadUtil = new ServiceCallableUtil();
					//批量抓取行情
					multiThreadUtil.setOperType("spiderDept");
					multiThreadUtil.setParamsMap(thrMap);
					multiThreadUtil.setOutTimerService(this);
					callList.add(multiThreadUtil);
				}
			}
		}
		
		ExecutorServiceUtil.submit(callList);
		ConstatFinalUtil.TIMER_LOG.info("----- 抓取交易网站结束 -----线程数:" + callList.size());
	}

	@Override
	public boolean spliderDeptService(ITradeService tradeService, JSONObject typeJSON)
	{
		String type = typeJSON.get("name") + "";
		String ctid = typeJSON.get("id") + "";
		
		List<ADept> insertDeptList = new ArrayList<ADept>();
		List<ADept> updateDeptList = new ArrayList<ADept>();
		
		//查询一下交易类型
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", ctid);
		ATradeType tradeType = this.websiteService.findOneTradeTypeService(condMap);
		try
		{
			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("moneytype", type);
			// bids是买入,asks是卖出
			JSONObject responseJSON = tradeService.queryDepth(paramsMap);
			//返回验证码
			if("0".equalsIgnoreCase(responseJSON.get("code") + ""))
			{
				JSONObject dataJSON = (JSONObject) responseJSON.get("data");
				// 卖出的单
				JSONArray asksArr = (JSONArray) dataJSON.get("asks");
				int count = 1;
				double sumAsksVol=0;
				for (Iterator iterator = asksArr.iterator(); iterator.hasNext();)
				{
					JSONObject asksTemp = (JSONObject) iterator.next();
					
					condMap.clear();
					condMap.put("wbid", tradeService.findWebsiteId() + "");
					condMap.put("ptype", ADeptEnum.PTYPE_SELL.getStatus() + "");
					condMap.put("otype", count + "");
					condMap.put("ctid", ctid);
					ADept dept = this.websiteService.findOneDeptService(condMap);
					boolean updateFlag = true;
					if (dept == null)
					{
						dept = new ADept();
						updateFlag = false;
					}
					
					sumAsksVol+=Double.valueOf(asksTemp.get("vol") + "");
					dept.setCtid(Integer.valueOf(ctid));
					dept.setWbid(tradeService.findWebsiteId());
					//设置汇率
					dept.setRate(tradeType.getRate());
					dept.setSouprice(Double.valueOf(asksTemp.get("rate") + ""));
					dept.setPrice(dept.getRate() * dept.getSouprice());
					dept.setVolnum(Double.valueOf(asksTemp.get("vol") + ""));
					dept.setOrdersnum(Integer.valueOf(asksTemp.get("count") + ""));
					dept.setPtype(ADeptEnum.PTYPE_SELL.getStatus());
					dept.setOtype(Byte.valueOf(count + ""));
					dept.setUpdatetime(new Date());
					dept.setMergevol(sumAsksVol);
					// 先查询是否存在
					if (updateFlag)
					{
						updateDeptList.add(dept);
						//this.websiteService.updateOneDeptService(dept);
					} else
					{
						dept.setCreatetime(new Date());
						insertDeptList.add(dept);
						//this.websiteService.saveOneDeptService(dept);
					}
					count++;
				}
				
				count = 1;
				double sumBidsVol=0;
				// 卖出的单
				JSONArray bidsArr = (JSONArray) dataJSON.get("bids");
				for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();)
				{
					JSONObject asksTemp = (JSONObject) iterator.next();
					
					condMap.clear();
					condMap.put("wbid", tradeService.findWebsiteId() + "");
					condMap.put("otype", count + "");
					condMap.put("ptype", ADeptEnum.PTYPE_BUY.getStatus() + "");
					condMap.put("ctid", ctid);
					ADept dept = this.websiteService.findOneDeptService(condMap);
					boolean updateFlag = true;
					if (dept == null)
					{
						dept = new ADept();
						updateFlag = false;
					}
					sumBidsVol+=Double.valueOf(asksTemp.get("vol") + "");
					dept.setCtid(Integer.valueOf(ctid));
					dept.setWbid(tradeService.findWebsiteId());
					dept.setRate(tradeType.getRate());
					dept.setSouprice(Double.valueOf(asksTemp.get("rate") + ""));
					dept.setPrice(dept.getRate() * dept.getSouprice());
					dept.setVolnum(Double.valueOf(asksTemp.get("vol") + ""));
					dept.setOrdersnum(Integer.valueOf(asksTemp.get("count") + ""));
					dept.setPtype(ADeptEnum.PTYPE_BUY.getStatus());
					dept.setOtype(Byte.valueOf(count + ""));
					dept.setUpdatetime(new Date());
					dept.setMergevol(sumBidsVol);
					// 先查询是否存在
					if (updateFlag)
					{
						updateDeptList.add(dept);
						//this.websiteService.updateOneDeptService(dept);
					} else
					{
						dept.setCreatetime(new Date());
						insertDeptList.add(dept);
						//this.websiteService.saveOneDeptService(dept);
					}
					count++;
				}
			}
			
			this.websiteService.updateBatchDeptService("1", insertDeptList);
			this.websiteService.updateBatchDeptService("2", updateDeptList);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOG.error(
					"抓取交易网站深度数据失败了," + tradeService.findWebsiteId(), e);
			return false;
		}
		return true;
	}

	@Override
	public void updateBatchUsersInfoService(AUsers users)
	{
		ConstatFinalUtil.SYS_LOG.info("----- 更新用户余额信息开始 -----" + users.getId());
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		Map<String, String> paramsMap = new HashMap<String, String>();
		
		/* 批量更新用户的账户信息 */
		List<AUsersAccount> usersAccountUpdateList = new ArrayList<AUsersAccount>() ; 
		
		//按照用户和网站分组，减少查询交易网站次数
		condMap.clear();
		condMap.put("usersid", users.getId() + "") ;
		condMap.put("status", "1") ; 
		condMap.put("groupby", "2");
		List<AUsersAccount> usersAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
		for (Iterator iterator = usersAccountList.iterator(); iterator
				.hasNext();)
		{
			AUsersAccount usersAccount = (AUsersAccount) iterator.next();
			
			condMap.clear();
			condMap.put("id", usersAccount.getWbid() + "");
			AWebsite website = this.websiteService.findOneWebsiteService(condMap);
			if (website == null || website.getStatus() == 0)
			{
				continue;
			}
			
			/* 保存用户的相关信息 */
			this.usersService.saveOneUsersAccountService(usersAccount);
		}
		
		/* 批量更新用户的余额信息 */
		this.usersService.updateBatchUsersAccountService("2", usersAccountUpdateList);
		ConstatFinalUtil.SYS_LOG.info("----- 更新用户余额信息结束 -----" + users.getId());
	}
	
	@Override
	public Map<String, Object> operCompareService(String type , Map<String, Object> paramMap) 
	{
		//ConstatFinalUtil.OUTER_LOG.info("===== 搬砖开始 =====");
		//coinid
		String ctid = paramMap.get("cid") + "";
		/* 有可能为空 */
		String wbid = paramMap.get("wbid") + "";
		if("null".equalsIgnoreCase(wbid))
		{
			wbid = ""; 
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//确定是否满足搬砖的条件
		/* 
		 * 所有取第一个渠道,交易量必须大于0.1个,少于则取第二个.
		 * 1,取所有交易网站买入价最高的.
		 * select * from a_dept where volnum > 0.1 and ptype = 0 order by price desc ; 
		 * 2,取所有交易网站卖出价最低的.
		 * select * from a_dept where volnum > 0.1 and ptype = 1 order by price ; 
		 * 
		 * 类型:0:买入,1:卖出
		 * 
		 * 交易时间必须在10以内
		 *  */
		Calendar now = Calendar.getInstance();
		
		Date edDate = now.getTime() ;
		/* 抓取多少秒以内的行情
		 * 默认是10秒;
		 *  */
		now.add(Calendar.SECOND, -Integer.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("dept.time")));
		Date stDate = now.getTime() ; 
//ConstatFinalUtil.SYS_LOG.info(stDate.toLocaleString() + "--->" + edDate.toLocaleString());
		PageInfoUtil pageInfo = new PageInfoUtil();
		pageInfo.setPageSize(100);
		//先取取所有交易网站买入价最低的.
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("wbid", wbid);
		condMap.put("st", this.dateUtil.formatDateTime(stDate));
		condMap.put("ed", this.dateUtil.formatDateTime(edDate));
		condMap.put("ptype", ADeptEnum.PTYPE_BUY.getStatus() + "");
		condMap.put("volnumdy", ConstatFinalUtil.SYSPRO_MAP.get("orders.trade.minnum"));
		condMap.put("orderby", "priceDesc");
		condMap.put("ctid", ctid);
		List<ADept> deptBuyList = this.websiteService.findCondListDeptService(pageInfo, condMap);
		ADept buyDept = null ; 
		if(deptBuyList.size() > 0 )
		{
			buyDept = deptBuyList.get(0);
		}
		
		//取所有交易网站卖出价最低的.
		condMap.clear();
		condMap.put("wbid", wbid);
		condMap.put("st", this.dateUtil.formatDateTime(stDate));
		condMap.put("ed", this.dateUtil.formatDateTime(edDate));
		condMap.put("ptype", ADeptEnum.PTYPE_SELL.getStatus() + "");
		condMap.put("volnumdy", ConstatFinalUtil.SYSPRO_MAP.get("orders.trade.minnum"));
		condMap.put("orderby", "priceAsc");
		condMap.put("ctid", ctid);
		List<ADept> deptSellList = this.websiteService.findCondListDeptService(pageInfo, condMap);
		ADept sellDept = null ; 
		if(deptSellList.size() > 0 )
		{
			sellDept = deptSellList.get(0);
		}
		
		resultMap.put("deptBuyList", deptBuyList);
		resultMap.put("deptSellList", deptSellList);
		
		if(buyDept != null && sellDept != null)
		{
			if("2".equalsIgnoreCase(type))
			{
				StringBuffer sb = new StringBuffer();
				pageInfo.setPageSize(5);
				
				//方法之间传递参数
				Map<String, Object> methodMap = new HashMap<String, Object>();
				//更新任务价格
				methodMap.put("uppriceFlag", "1");
				/*
				 * 查询所有的用户,会按照更新时间正着排序,
				 * 查询出来的是不同的用户,一次性处理5个用户
				 * 查询人民币的收益
				 */
				condMap.clear();
				condMap.put("coinid", TradeUtil.MAIN_COINID + "");
				condMap.put("users_status",  "1");
				condMap.put("prostatus",  "1");
				//按照用户分组,查询的是不同的用户
				condMap.put("groupby",  "1");
				List<AUsersAccount> usersAccountList = this.usersService.findCondListUsersAccountService(pageInfo, condMap);
				outer:for (Iterator iterator = usersAccountList.iterator(); iterator
						.hasNext();)
				{
					AUsersAccount usersAccount = (AUsersAccount) iterator.next();
					if(new Date().getTime() - usersAccount.getUpdatetime().getTime() < ConstatFinalUtil.SECOND * 5)
					{
						continue ;
					}
					
					long st = System.currentTimeMillis(); 
					int totalCount = 0 ; 
					int succedCount = 0 ; 
					sb.append("用户id:" + usersAccount.getId() + ";用户名:" + usersAccount.getUsername() + ";" + "币种Id:" + ctid + ";") ;
					sb.append("卖单数量:" + deptSellList.size() + ";最高的金额:" + sellDept.getPrice() + ";数量:" + sellDept.getMergevol() + ";");
					sb.append("买单数量:" + deptBuyList.size() + ";最低的金额:" + buyDept.getPrice() + ";数量:" + buyDept.getMergevol() + ";");
					//每一个交易都要处理,多搬几次砖
					inner:for (int i = 0; i < deptSellList.size(); i++)
					{
						ADept sellDeptTemp = deptSellList.get(i);
						for (int j = 0; j < deptBuyList.size(); j++)
						{
							ADept buyDeptTemp = deptBuyList.get(j) ; 
							totalCount ++ ; 
							//必须是买的价格大于卖的价格,增加循环的次数,价格为负数也搬砖
							/*if(buyDeptTemp.getPrice() > sellDeptTemp.getPrice())
							{*/
								succedCount ++ ; 
								//确定是否进行搬砖,创建任务成功,停止
								if(this.operTaskCreateService(sellDeptTemp, buyDeptTemp ,usersAccount, methodMap))
								{
									break inner ; 
								}
							/*}*/
						}
					}
					long ed = System.currentTimeMillis(); 
					methodMap.put("uppriceFlag", "0");
					sb.append("循环总次数:" + totalCount + ";" + ";价格满足次数:" + succedCount + ";") ;
					sb.append("耗时(毫秒):" + (ed - st) + ";");
					ConstatFinalUtil.SYS_LOG.info(sb);
				}
			}
			
			resultMap.put("sellDept", sellDept);
			resultMap.put("buyDept", buyDept);
		}
		//ConstatFinalUtil.OUTER_LOG.info("===== 搬砖结束 =====");
		return resultMap; 
	}
	
	public Map<String, Object> deptRateService(String type , Map<String, Object> paramMap) 
	{
		//ConstatFinalUtil.OUTER_LOG.info("===== 搬砖开始 =====");
		//coinid
		String ctid = paramMap.get("cid") + "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//确定是否满足搬砖的条件
		/* 
		 * 所有取第一个渠道,交易量必须大于0.1个,少于则取第二个.
		 * 1,取所有交易网站买入价最高的.
		 * select * from a_dept where volnum > 0.1 and ptype = 0 order by price desc ; 
		 * 2,取所有交易网站卖出价最低的.
		 * select * from a_dept where volnum > 0.1 and ptype = 1 order by price ; 
		 * 
		 * 类型:0:买入,1:卖出
		 * 
		 * 交易时间必须在10以内
		 *  */
		Calendar now = Calendar.getInstance();
		
		Date edDate = now.getTime() ; 
		now.add(Calendar.SECOND, -10);
		Date stDate = now.getTime() ; 
//ConstatFinalUtil.SYS_LOG.info(stDate.toLocaleString() + "--->" + edDate.toLocaleString());
		PageInfoUtil pageInfo = new PageInfoUtil();
		pageInfo.setPageSize(100);
		//先取取所有交易网站买入价最低的.
		Map<String, Object> condMap = new HashMap<String, Object>();
//		condMap.put("st", this.dateUtil.formatDateTime(stDate));
//		condMap.put("ed", this.dateUtil.formatDateTime(edDate));
		condMap.put("ptype", ADeptEnum.PTYPE_BUY.getStatus() + "");
		condMap.put("volnumdy", ConstatFinalUtil.SYSPRO_MAP.get("orders.trade.minnum"));
		condMap.put("orderby", "priceDesc");
		condMap.put("ctid", ctid);
		
		//按照网站汇总
		condMap.put("groupby", "wbid");
		List<ADept> deptBuyList = this.websiteService.findCondListDeptService(pageInfo, condMap);
		
		//取所有交易网站卖出价最低的.
		condMap.clear();
//		condMap.put("st", this.dateUtil.formatDateTime(stDate));
//		condMap.put("ed", this.dateUtil.formatDateTime(edDate));
		condMap.put("ptype", ADeptEnum.PTYPE_SELL.getStatus() + "");
		condMap.put("volnumdy", ConstatFinalUtil.SYSPRO_MAP.get("orders.trade.minnum"));
		condMap.put("orderby", "priceAsc");
		condMap.put("ctid", ctid);
		//按照网站汇总
		condMap.put("groupby", "wbid");
		List<ADept> deptSellList = this.websiteService.findCondListDeptService(pageInfo, condMap);
		
		resultMap.put("deptBuyList", deptBuyList);
		resultMap.put("deptSellList", deptSellList);
		return resultMap; 
	}

	/**
	 * 任务创建
	 */
	private boolean operTaskCreateService(ADept sellDept , ADept buyDept , AUsersAccount usersAccount , Map<String, Object> methodMap) 
	{
		AWebsite sellWebsite = sellDept.getWebsiteObj() ;
		ATradeType sellTradeType = sellDept.getTradeTypeObj() ;
		double num = 0 ; 
		//考虑数量,以最少的数量为基准
		if(buyDept.getMergevol() > sellDept.getMergevol())
		{
			num = sellDept.getMergevol();
		}else if(sellDept.getMergevol() > buyDept.getMergevol())
		{
			num = buyDept.getMergevol();
		}
		
		//由于取的是合并交易量,所以取合并交易量的80%;提高成交概率
		num = num * Double.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("orders.webnum.percent")) ;
		if(!"1".equalsIgnoreCase(buyDept.getUpdateFlagStr()))
		{
			//价格做修改,买单要低
			buyDept.setPrice(buyDept.getPrice() - Double.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("orders.webprice")));
			buyDept.setSouprice(buyDept.getPrice() / buyDept.getRate());
			buyDept.setUpdateFlagStr("1");
		}
		
		if(!"1".equalsIgnoreCase(buyDept.getUpdateFlagStr()))
		{
			//卖单要高
			sellDept.setPrice(sellDept.getPrice() + Double.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("orders.webprice")));
			sellDept.setSouprice(sellDept.getPrice() / sellDept.getRate());
			sellDept.setUpdateFlagStr("1");
		}
		
		double chprice = buyDept.getPrice() - sellDept.getPrice() ; 
		double priceRate = chprice / (buyDept.getPrice() + sellDept.getPrice()) ;
		chprice = doubleOperUtil.round(chprice, 5, RoundingMode.DOWN.ordinal());
		double totalprift = chprice * num ;
		totalprift = doubleOperUtil.round(totalprift, 5, RoundingMode.DOWN.ordinal()) ; 
		
		/*if(chprice < 0)
		{
			return false ; 
		}*/
		
		String info = "卖出价:"+ sellDept.getSouprice() + "*" + sellDept.getRate() + "=" + sellDept.getPrice()  + ",数量:"+ sellDept.getVolnum() + 
				",网站id:"+ sellDept.getWbid() + "," + sellDept.getWebsiteObj().getName() + ";" +   
				"买入价:"+ buyDept.getSouprice() + "*" + buyDept.getRate() + "=" + buyDept.getPrice()  + ",数量:"+ buyDept.getVolnum() +
				",网站id:"+ buyDept.getWbid() + "," + buyDept.getWebsiteObj().getName() + ";" +   
				"差价:" + chprice + ",总利润:" + totalprift + ";"; 
		//ConstatFinalUtil.OUTER_LOG.info("差价信息:" + info);
		
		//更新价格只更新一次
		if("1".equalsIgnoreCase(methodMap.get("uppriceFlag") + ""))
		{
			//更新进行中的任务价格
			this.updateTaskPrice(sellDept, buyDept , methodMap);
			//ConstatFinalUtil.SYS_LOG.info("更新进行中任务价格:卖价格:{};买价格:{},方法参数:{}", sellDept,buyDept,methodMap);
		}
		
			
		//判断交易数量是否够
		//差价大于用户制定的差价(适应于btc),或者总利润越过制定的利润(适应于ltc)
		/*if((usersAccount.getPrift() <= chprice ) 
			|| (usersAccount.getPrift() <= chprice * num))*/
		/* 价格率大于用户设置的就搬砖 */
		if(usersAccount.getPrift() <= priceRate)
		{
			//站在用户的角度:交易数量,要买的数量
			double tradenum = num ;
			//站在用户的角度:交易数量,要买的数量
			//0:不验证余额,1:验证余额;只有都是是true的时候才可以交易,否则不能交易
			if("1".equalsIgnoreCase(ConstatFinalUtil.SYSPRO_MAP.get("trade.auth.balance")))
			{
				//验证余额
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				paramsMap.put("usersid" , usersAccount.getUsersid() + "");
				paramsMap.put("sellDept" , sellDept);
				paramsMap.put("buyDept" , buyDept);
				paramsMap.put("num" , num ) ;
				Map<String, Object> resultMap = this.validBalance(paramsMap);
				if(!("1".equalsIgnoreCase(resultMap.get("sellFlag") + "") && "1".equalsIgnoreCase(resultMap.get("buyFlag") + "")))
				{
					//ConstatFinalUtil.SYS_LOG.info("余额不足:用户:{},用户设置收益:{},信息:{}", usersAccount.getId() , usersAccount.getPrift() , info);
					return false ; 
				}
				
				tradenum = Double.valueOf(resultMap.get("tradenum") + "");
				/*ConstatFinalUtil.SYS_LOG.error("验证余额标志:" + ConstatFinalUtil.SYSPRO_MAP.get("trade.auth.balance") + 
						";买标志(买币)" + buyFlag + ";卖的标志(卖币):" + sellFlag);
				*/
			}
			
			//往用户任务表中增加
			AUsersTask usersTask = new AUsersTask();
			
			usersTask.setUsersid(usersAccount.getUsersid());
			//收益币种默认usdt
			usersTask.setPriftcoinid(TradeUtil.USD_COINID);
			usersTask.setSellctid(sellDept.getCtid());
			usersTask.setBuyctid(buyDept.getCtid());
			
			//订单完成的时候会计算收益
			usersTask.setPrift(0);
			usersTask.setSellwbid(sellDept.getWbid());
			usersTask.setBuywbid(buyDept.getWbid());
			
			//数量减半,最少为1个币
			usersTask.setDeptnum(num);
			usersTask.setSousellprice(sellDept.getSouprice());
			usersTask.setSellprice(sellDept.getPrice());
			usersTask.setTasksellprice(sellDept.getPrice());
			usersTask.setSoubuyprice(buyDept.getSouprice());
			usersTask.setBuyprice(buyDept.getPrice());
			usersTask.setTaskbuyprice(buyDept.getPrice());
			usersTask.setPricecha(chprice);
			//系统创建默认开始
			usersTask.setStatus(AUsersTaskEnum.STATUS_GOING.getStatus());
			usersTask.setSoutype(AUsersTaskEnum.SOUTYPE_SYSTEM.getStatus());
			usersTask.setCreatetime(new Date());
			usersTask.setUpdatetime(new Date());
			usersTask.setFinishtime(new Date());
			
			//币不够卖,
			usersTask.setTotalnum(tradenum);
			//设置币的交易手续费
			if(sellWebsite != null && sellTradeType != null)
			{
				JSONObject moneyStatusJSON = sellWebsite.getMoneyStatusJSON() ;
				moneyStatusJSON = (JSONObject) moneyStatusJSON.get(sellTradeType.getId() + "");
				usersTask.setFeenum(this.doubleOperUtil.mul(usersTask.getTotalnum(), Double.valueOf(moneyStatusJSON.get("tradeFee") + "")));
			}else
			{
				usersTask.setFeenum(usersTask.getTotalnum());
			}
			
			//计算手续费
			Map<String, Double> resultMap = this.removeFee(usersTask.getTotalnum() , usersTask);
			double removefee = resultMap.get("rescha");
			/* 价格之差/价格之和 */
			double reschaRate = resultMap.get("reschaRate");
			
			//去掉手续费以后的收益还大于用户定制的收益,就创建任务
			if(usersAccount.getPrift() <= reschaRate && removefee > 0 )
			{
				/* 增加上差价率 */
				info = "差价率:" + doubleOperUtil.round(reschaRate, 5, RoundingMode.DOWN.ordinal()) + ";" + info; 
				//数量以能买的为主,原则:保持btc数量不变
				usersTask.setName(info);
				usersTask.setContent(info);
				
				usersTask.setSouprift(removefee);
				//存储订单总任务
				JSONObject resdbJSON = this.ordersService.saveOneUsersTaskService(usersTask);
				ConstatFinalUtil.SYS_LOG.info(usersAccount.getId() + "是usersAccountid---- 创建任务信息 ----" + resdbJSON);
				//按照币种和用户,更新时间
				usersAccount.setUpdatetime(new Date());
				this.usersService.updateBatchUsersAccountService("updateUpdateTime" , usersAccount);
				/* 只要创建成功就下单 */
				if("0".equalsIgnoreCase(resdbJSON.getString("code")))
				{
					/* 只要一创建任务,马上下单 */
					this.operTaskTradeService(usersTask);
				}
				/*
				//更新用户的金额信息
				condMap.clear();
				condMap.put("id", usersAccount.getUsersid() + "");
				AUsers users = this.usersService.findOneUsersService(condMap);
				*/
				return true ; 
			}
		}else
		{
			//ConstatFinalUtil.SYS_LOG.info("收益不够:用户:{},用户设置收益:{},信息:", usersAccount.getId() , usersAccount.getPrift() , info);
		}
		return false ; 
	}
	
	/**
	 * 验证余额是否够
	 * 根据 用户id,交易网站,交易币种
	 * 分买币和卖币两种情况
	 * 
	 * 不管是买币还是卖币,都有最小的交易金额;(设定最小交易金额)
	 */
	private Map<String, Object> validBalance(Map<String, Object> paramsMap)
	{
		/* 最小交易的金额----法币 */
		double minTradeMoney = 0 ; 
		
		//AUsersAccount usersAccount = (AUsersAccount) paramsMap.get("usersAccount");
		String usersid = paramsMap.get("usersid") + ""; 
		ADept sellDept = (ADept) paramsMap.get("sellDept");
		ADept buyDept = (ADept) paramsMap.get("buyDept");
		double num = Double.valueOf(paramsMap.get("num") + "") ;
		double tradenum = num ; 
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> condMap = new TreeMap<String, Object>();
		
		ATradeType sellTradeType = sellDept.getTradeTypeObj() ;
		ATradeType buyTradeType = buyDept.getTradeTypeObj() ;
		
		condMap.clear();
		condMap.put("usersid", usersid + "");
		condMap.put("wbid", sellDept.getWbid() + "");
		condMap.put("coinid", sellTradeType.getFromcoinid() + "");
		condMap.put("status", AUsersAccountEnum.STATUS_ENABLE.getStatus() + "");
		condMap.put("cache", "true");
		condMap.put("expirTime", 5);
		/*
		 * 查询的结果肯定只有一条
		 * */
		List<AUsersAccount> sellCoinAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
		
		AUsersAccount usersSellAccount = null ; 
		/*
		 * 最大交易量都是一致的,所以取最后一个就可以
		 * 买卖的交易币种都是一致的,所以取哪个都可以.
		 */
		inner:for (Iterator iterator2 = sellCoinAccountList.iterator(); iterator2
				.hasNext();)
		{
			usersSellAccount = (AUsersAccount) iterator2.next();
			
			/*
			 * 查询虚拟币的用户设置的最大交易量
			 */
			if(usersSellAccount.getTrademaxnum() > 0 && usersSellAccount.getTrademaxnum() < num)
			{
				tradenum = usersSellAccount.getTrademaxnum() ; 
			}
			
			/**
			 * tradeNumIgnorce:已经成交了一部分,剩下的部分成交不考虑最小交易量
			 */
			if(!"true".equalsIgnoreCase(paramsMap.get("tradeNumIgnorce") + "")
				&& usersSellAccount.getTrademinnum() > 0 && usersSellAccount.getTrademinnum() > num )
			{
				/* 最小量太小了,不交易 */
				resultMap.put("enouth", num);
				return resultMap ; 
			}
			
			/*
			 * 查询法币的余额是否够,
			 * 从交易网站中的交易类型中获取法币的金额,带上用户名
			 * 一个交易网站可以有多个用户名
			 */
			condMap.clear();
			condMap.put("usersid", usersid + "");
			condMap.put("wbid", sellDept.getWbid() + "");
			//法币
			condMap.put("coinid", sellTradeType.getTocoinid() + "");
			condMap.put("keywordEq", usersSellAccount.getUsername() + "");
			condMap.put("status", AUsersAccountEnum.STATUS_ENABLE.getStatus() + "");
			condMap.put("cache", "true");
			condMap.put("expirTime", 5);
			//以上条件可以确定一条记录
			List<AUsersAccount> sellCoinFaAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
			if(sellCoinFaAccountList.size() > 0)
			{
				AUsersAccount usersAccountSellFa = sellCoinFaAccountList.get(0);
				/* 获取的是法币的最小交易量 */
				minTradeMoney = usersAccountSellFa.getTrademinnum() ;
				
				/*
				 * 不管是买币还是卖币,都有最小的交易金额;(设定最小交易金额)
				 * 取的是法币,钱够买币
				 * */
				if(usersAccountSellFa.getBalance() - sellDept.getSouprice() * tradenum >= 0)
				{
					/* 有最小交易金额 */
					if(minTradeMoney > 0 && sellDept.getSouprice() * tradenum > minTradeMoney)
					{
						resultMap.put("buyFlag", "1");
					}
					/* 木有最小交易金额 */
					if(minTradeMoney == 0 )
					{
						resultMap.put("buyFlag", "1");
					}
					break ;
				}
			}
		}
		
		if(usersSellAccount != null)
		{
			/*
			 * 查询的结果肯定只有一条
			 * 
			 * 查询法币的余额是否够,
			 * 从交易网站中的交易类型中获取法币的金额,带上用户名
			 * 一个交易网站可以有多个用户名
			 */
			condMap.clear();
			condMap.put("usersid", usersid + "");
			condMap.put("wbid", buyDept.getWbid() + "");
			//法币
			condMap.put("coinid", buyTradeType.getTocoinid() + "");
			condMap.put("keywordEq", usersSellAccount.getUsername() + "");
			condMap.put("status", AUsersAccountEnum.STATUS_ENABLE.getStatus() + "");
			condMap.put("cache", "true");
			condMap.put("expirTime", 5);
			//以上条件可以确定一条记录
			List<AUsersAccount> buyCoinFaAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
			if(buyCoinFaAccountList.size() > 0 )
			{
				minTradeMoney = buyCoinFaAccountList.get(0).getTrademinnum() ; 
			}
			
			/*
			 * 查询的结果肯定只有一条
			 * 同一个用户同一个网站可以有多个账户
			 * 查看买方网站的id虚拟币(btc)余额是否够
			 * 卖币
			 */
			condMap.clear();
			condMap.put("usersid", usersid + "");
			condMap.put("wbid", buyDept.getWbid() + "");
			condMap.put("coinid", buyTradeType.getFromcoinid() + "");
			condMap.put("status", AUsersAccountEnum.STATUS_ENABLE.getStatus() + "");
			condMap.put("cache", "true");
			condMap.put("expirTime", 5);
			List<AUsersAccount> buyCoinAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
			if(buyCoinAccountList.size() > 0)
			{
				for (Iterator iterator = buyCoinAccountList.iterator(); iterator
						.hasNext();) {
					AUsersAccount usersbuyAccount = (AUsersAccount) iterator.next();
					/* 不管是买币还是卖币,都有最小的交易金额;(设定最小交易金额) 
					 * */
					//取的是法币,钱够买币
					/* if(usersbuyAccount.getBalance() - buyDept.getMergevol() >= 0) */
					 if(usersbuyAccount.getBalance() - tradenum >= 0) 
					{
						/* 有最小交易金额 */
						if(minTradeMoney > 0 && sellDept.getSouprice() * tradenum > minTradeMoney)
						{
							resultMap.put("sellFlag", "1");
						}
						/* 木有最小交易金额 */
						if(minTradeMoney == 0 )
						{
							resultMap.put("sellFlag", "1");
						}
						break ; 
					}
				}
			}
		}
		
		resultMap.put("tradenum", tradenum);
		return resultMap ; 
	}
	
	/**
	 * 更新正在执行任务价格
	 * 更新价格只取最合理的买卖价
	 * 任务首次执行不成功,调整价格,让币成交
	 */
	private void updateTaskPrice(ADept sellDept , ADept buyDept, Map<String, Object> methodMap)
	{
		Map<String, Object> condMap = new HashMap<String, Object>() ;
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		
		ATradeType sellTradeType = sellDept.getTradeTypeObj() ;
		ATradeType buyTradeType = buyDept.getTradeTypeObj() ;
		
		/* 交易最长时间 单位:秒*/
		int maxTime = Integer.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("orders.trade.maxTime")) * ConstatFinalUtil.SECOND; 
		//仅查询未调整过价格的任务
		condMap.clear();
		condMap.put("status", AUsersTaskEnum.STATUS_GOING.getStatus() + "");
		List<AUsersTask> usersTaskList = this.ordersService.findCondListUsersTaskService(null, condMap);
		for (Iterator iterator = usersTaskList.iterator(); iterator
				.hasNext();)
		{
			AUsersTask usersTask = (AUsersTask) iterator.next();
			//小于1分钟不考虑更新价格,如果不成交,直接交易
			if(new Date().getTime() - usersTask.getCreatetime().getTime() < maxTime)
			{
				continue ; 
			}
			
			ATradeType tradeType = usersTask.getBuyTradeTypeObj() ;
			
			ATradeType deptType = sellDept.getTradeTypeObj();
			//如果原币种不一样,就不更新
			if(deptType != null && tradeType != null && tradeType.getFromcoinid() != deptType.getFromcoinid())
			{
				return ;
			}
			
			//任务的买数量与卖数量不一致时,取任务应买数量与卖数量最少的一笔
			double buynum = usersTask.getTotalnum() - usersTask.getBuynum() ;
			double sellnum = usersTask.getTotalnum() - usersTask.getSellnum() ;
			//取未完成任务中最少的那个.
			double num = buynum ;
			if(buynum > 0 )
			{
				if(buynum > sellnum)
				{
					num = sellnum ; 
				}
			}else
			{
				num = sellnum ;
			}
			
			//判断余额是否够
			//验证余额
			//paramsMap.put("usersAccount" , usersAccount);
			paramsMap.put("usersid" , usersTask.getUsersid() + "");
			paramsMap.put("sellDept" , sellDept);
			paramsMap.put("buyDept" , buyDept);
			paramsMap.put("num" , num) ;
			paramsMap.put("tradeNumIgnorce" , "true") ;
			Map<String, Object> resultMap = this.validBalance(paramsMap);
			
			String buyprice = "原始价格(买):" + usersTask.getSoubuyprice() + ";cny:" + usersTask.getBuyprice() + ";";
			String sellprice = "原始价格(卖):" + usersTask.getSousellprice() + ";cny:" + usersTask.getSellprice() + ";";
			boolean upflag = false ; 
			//站在网站角度:买单--现价格比任务中的价格要低
			if(usersTask.getSoutype() == AUsersTaskEnum.SOUTYPE_SYSTEM.getStatus())
			{
				//系统创建
				//卖币,收益一半就可以更新价格
				/*if(usersTask.getTaskbuyprice() - buyDept.getPrice() <= usersTask.getSouprift() / 2
						&& usersTask.getTaskbuyprice() - buyDept.getPrice() > 0
						&& "1".equalsIgnoreCase(resultMap.get("sellFlag") + ""))
				{*/
				if("1".equalsIgnoreCase(resultMap.get("sellFlag") + ""))
				{
					usersTask.setBuywbid(buyDept.getWbid());
					usersTask.setBuyctid(buyDept.getCtid());
					usersTask.setSoubuyprice(buyDept.getSouprice());
					usersTask.setBuyprice(buyDept.getPrice());
					upflag = true ; 
				}
				
				//买币,收益一半就可以更新价格
				/*if(sellDept.getPrice() - usersTask.getTasksellprice() <= usersTask.getSouprift() / 2 
						&& sellDept.getPrice() - usersTask.getTasksellprice() > 0
						&& "1".equalsIgnoreCase(resultMap.get("buyFlag") + ""))
				{*/
				if("1".equalsIgnoreCase(resultMap.get("buyFlag") + ""))
				{
					usersTask.setSellctid(sellDept.getCtid());
					usersTask.setSousellprice(sellDept.getSouprice());
					usersTask.setSellprice(sellDept.getPrice());
					usersTask.setSellwbid(sellDept.getWbid());
					
					upflag = true ; 
				}
			}else
			{
				//类型更新价格的标签
				boolean souflag = false ;
				
				//判断收益
				if(usersTask.getTaskbuyprice() == 0 && buyDept.getPrice() - sellDept.getPrice() < usersTask.getSouprift())
				{
					//不值得搬砖
					continue ;
				}
				
				if(usersTask.getTaskbuyprice() == 0 && "1".equalsIgnoreCase(resultMap.get("sellFlag") + "")
					&& "1".equalsIgnoreCase(resultMap.get("buyFlag") + ""))
				{
					//第一次必须可以买和卖才行
				}else
				{
					continue ; 
				}
				
				if(buyDept.getPrice() - sellDept.getPrice() < usersTask.getSouprift() / 2 )
				{
					//不值得搬砖
					continue ;
				}
				
				if(usersTask.getSoutype() == 1)
				{
					//1:cny-usd;  cny:买币,usd:卖币
					if(sellTradeType.getTocoinid() == TradeUtil.CNY_COINID && buyTradeType.getTocoinid() == TradeUtil.USD_COINID)
					{
						souflag = true ; 
					}
				}else if(usersTask.getSoutype() == 2)
				{
					//2:usd-cny   usd:买币,cny:卖币
					if(sellTradeType.getTocoinid() == TradeUtil.USD_COINID && buyTradeType.getTocoinid() == TradeUtil.CNY_COINID)
					{
						souflag = true ; 
					}
				}
				
				if(souflag)
				{
					//卖币,收益一半就可以更新价格
					if("1".equalsIgnoreCase(resultMap.get("sellFlag") + ""))
					{
						if(usersTask.getTaskbuyprice() == 0)
						{
							usersTask.setBuywbid(buyDept.getWbid());
							usersTask.setBuyctid(buyDept.getCtid());
							usersTask.setSoubuyprice(buyDept.getSouprice());
							usersTask.setBuyprice(buyDept.getPrice());
							usersTask.setTaskbuyprice(usersTask.getBuyprice());
							
							upflag = true ;
						}else
						{
							if(usersTask.getTaskbuyprice() - buyDept.getPrice() <= usersTask.getSouprift() / 2
									&& usersTask.getTaskbuyprice() - buyDept.getPrice() > 0)
							{
								usersTask.setBuywbid(buyDept.getWbid());
								usersTask.setBuyctid(buyDept.getCtid());
								usersTask.setSoubuyprice(buyDept.getSouprice());
								usersTask.setBuyprice(buyDept.getPrice());
								
								upflag = true ; 
							}
						}
					}
					
					//买币,收益一半就可以更新价格
					if("1".equalsIgnoreCase(resultMap.get("buyFlag") + ""))
					{
						if(usersTask.getTasksellprice() == 0)
						{
							usersTask.setSellctid(sellDept.getCtid());
							usersTask.setSousellprice(sellDept.getSouprice());
							usersTask.setSellprice(sellDept.getPrice());
							usersTask.setSellwbid(sellDept.getWbid());
							
							upflag = true ;
						}else
						{
							if(sellDept.getPrice() - usersTask.getTasksellprice() <= usersTask.getSouprift() / 2 
									&& sellDept.getPrice() - usersTask.getTasksellprice() > 0)
							{
								usersTask.setSellctid(sellDept.getCtid());
								usersTask.setSousellprice(sellDept.getSouprice());
								usersTask.setSellprice(sellDept.getPrice());
								usersTask.setSellwbid(sellDept.getWbid());
								
								if(usersTask.getTasksellprice() == 0)
								{
									usersTask.setTasksellprice(usersTask.getSellprice());
								}
								upflag = true ; 
							}
						}
					}
				}
			}
			
			if(upflag)
			{
				usersTask.setUpdatetime(new Date());
				JSONObject resDBJSON = this.ordersService.updateOneUsersTaskService(usersTask);
				if(Integer.valueOf(resDBJSON.get("code") + "") > 0 )
				{
					ConstatFinalUtil.SYS_LOG.info(usersTask.getId() + "--更新进行中任务的价格--状态:" + usersTask.getStatusStr() 
						+ ";类型:" + usersTask.getSoutypeStr() + ";" + resDBJSON.get("code") + ";"
						+ buyprice + sellprice);
					//更新价格成功
					methodMap.put("uppriceFlag", "0");
				}
				
			}
		}
	}
	
	/**
	 * 收益中扣除手续费
	 * 
	 * 搬砖成功计算再回到原始位置时需要付出的代码
	 * @param usersTask
	 * @return
	 */
	public Map<String, Double> removeFee(double num , AUsersTask usersTask)
	{
		Map<String, Double> resultMap = new HashMap<String, Double>();
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		//查询网站类型
		condMap.clear();
		condMap.put("id", usersTask.getSellwbid() + "");
		AWebsite sellWebsite = this.websiteService.findOneWebsiteService(condMap);
		
		condMap.clear();
		condMap.put("id", usersTask.getBuywbid() + "");
		AWebsite buyWebsite = this.websiteService.findOneWebsiteService(condMap);
		
		//交易类型
		condMap.clear();
		condMap.put("id", usersTask.getSellctid() + "");
		ATradeType sellTradeType = this.websiteService.findOneTradeTypeService(condMap);
		condMap.clear();
		condMap.put("id", usersTask.getBuyctid() + "");
		ATradeType buyTradeType = this.websiteService.findOneTradeTypeService(condMap);
		
		
		double sellTradeFee = 0 ;
		double sellWithChange = 0 ; 
		
		JSONObject sellTradeFeeJSON = null  ;
		//sell,卖单,(买币)手续费
		JSONObject sellMonJSON = sellWebsite.getMoneyStatusJSON();
		JSONObject sellFeeJSON = sellWebsite.getFeeJSON();
		JSONObject sellCtJSON = (JSONObject) sellMonJSON.get(usersTask.getSellctid() + ""); 
		sellTradeFeeJSON = (JSONObject) sellFeeJSON.get(sellTradeType.getFromcoinid() + ""); 
		//交易手续费,买入扣除的是btc,卖出扣除的是法币
		sellTradeFee = Double.valueOf(sellCtJSON.get("tradeFee") + "") * num * usersTask.getSellprice(); 
		//虚拟币的手续费是固定的,交易网站:卖站提现,充值到买站
		sellWithChange = 0.0002 * usersTask.getSellprice() ; 
			
		resultMap.put("sellTradeFee", sellTradeFee);
		resultMap.put("sellWithChange", sellWithChange);
		
		double buyTradeFee = 0 ;
		double buyWithChange = 0 ; 
		//buy,买单,(卖币)手续费
		JSONObject buyMonJSON = buyWebsite.getMoneyStatusJSON();
		JSONObject buyFeeJSON = buyWebsite.getFeeJSON();
		JSONObject buyCtJSON = (JSONObject) buyMonJSON.get(usersTask.getBuyctid() + ""); 
		JSONObject buyTradeFeeJSON = (JSONObject) buyFeeJSON.get(buyTradeType.getTocoinid() + ""); 
		//交易手续费,买入扣除的是btc,卖出扣除的是法币
		buyTradeFee = Double.valueOf(buyCtJSON.get("tradeFee") + "") * num * usersTask.getBuyprice();
		//虚拟币的手续费是固定的,交易网站:买站提现,充值到卖站,法币统一是cny
		buyWithChange = num * usersTask.getBuyprice() * Double.valueOf(buyTradeFeeJSON.get("withdraw") + "") ;
		
		//充值手续费,如果币种不一样
		if(sellTradeType != null && sellTradeFeeJSON != null)
		{
			//如果币种一样,肯定是cny
			buyWithChange += num * usersTask.getBuyprice() * Double.valueOf(sellTradeFeeJSON.get("recharge") + "") ; 
		}
		resultMap.put("buyTradeFee", buyTradeFee);
		resultMap.put("buyWithChange", buyWithChange);
	
		//将差价去掉,cny
		double chaprice = usersTask.getBuyprice() * num - usersTask.getSellprice()  * num; 
		double sellfee = sellTradeFee + sellWithChange  ;
		double buyfee = buyTradeFee + buyWithChange ; 
		double rescha = chaprice - sellfee  - buyfee; 
		double reschaRate = (usersTask.getBuyprice() - usersTask.getSellprice() ) / (usersTask.getBuyprice() + usersTask.getSellprice() ); 
		
		resultMap.put("sellfee", sellfee);
		resultMap.put("buyfee", buyfee);
		resultMap.put("totalfee", sellfee + buyfee);
		resultMap.put("rescha", rescha);
		resultMap.put("reschaRate", reschaRate);
		//ConstatFinalUtil.SYS_LOG.info(chaprice + "-- 前手续费后 -- " + rescha + ",数量:" + num + ",币种:" + buyTradeType.getName());
		return resultMap;
	}

	/**
	 * 更新任务订单
	 * @param dept
	 */
	public void operTaskExecuteService(String flag) 
	{
		/* 对flag代码初始化 */
		if(flag == null)
		{
			flag = "" ; 
		}
		if("".equalsIgnoreCase(flag))
		{
			return ; 
		}
		
		//查询所有正在进行的任务
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("status", AUsersTaskEnum.STATUS_GOING.getStatus());
		List<AUsersTask> usersTaskList = this.ordersService.findCondListUsersTaskService(null, condMap);
		
		//对任务的用户进行分组
		List<String> usersidList = new ArrayList<String>();
		outer:for (Iterator iterator = usersTaskList.iterator(); iterator.hasNext();)
		{
			AUsersTask usersTask = (AUsersTask) iterator.next();
			
			/* 第一次访问 */
			if("first".equalsIgnoreCase(flag))
			{
				//先处理查询挂单,处理挂单操作,挂单不处理,就不下新单
				condMap.clear();
				condMap.put("utid", usersTask.getId() + "");
				condMap.put("status", AUsersTaskOrderEnum.STATUS_ORDERING.getStatus());
				List<AUsersTaskOrder> usersTaskOrderList = this.ordersService.findCondListUsersTaskOrderService(null, condMap);
				inner:for (Iterator iterator2 = usersTaskOrderList.iterator(); iterator2
						.hasNext();)
				{
					AUsersTaskOrder usersTaskOrder = (AUsersTaskOrder) iterator2
							.next();
					/*
					 * 如果当前有订单木有成交,发现订单的价格木有变化,就不用撤销订单;
						如果订单已经成交了,修改订单的状态(需要先查询一下订单)
					 * */
					//更新任务,处理挂单
					boolean cancelFlag = this.findTaskOrdersService(usersTaskOrder);
					/* 如果订单的状态还是挂单,并且,价格发生了变化
					 * 如果价格等于买的价格
					 * 如果价格等于卖的价格
					 *  */
					if(usersTaskOrder.getStatus() == AUsersTaskOrderEnum.STATUS_ORDERING.getStatus() 
						/* 任务的类型必须是系统创建的才会撤单 */
						&& usersTask.getSoutype() == AUsersTaskEnum.SOUTYPE_SYSTEM.getStatus()
						&&
						(
							/* 任务会更新价格,如果发现订单的价格和任务的价格不一样,撤单 */
							(usersTaskOrder.getPrice() != usersTask.getBuyprice() && 
							usersTaskOrder.getOrdertype() == AUsersTaskOrderEnum.ORDERTYPE_SELL.getStatus() )
							||
							(
								usersTaskOrder.getPrice() != usersTask.getSellprice() && 
								usersTaskOrder.getOrdertype() == AUsersTaskOrderEnum.ORDERTYPE_BUY.getStatus()
							)
						))
					{
						cancelFlag = this.cancelTaskOrdersService(usersTaskOrder) ;
					}
					if(cancelFlag)
					{
						/* 设置一下总价格 */
						usersTaskOrder.setTotalprice(usersTaskOrder.getPrice() * usersTaskOrder.getTradeedval());
						
						//将用户id增加到用户查询余额的列表中
						if(!usersidList.contains(usersTask.getUsersid() + ""))
						{
							usersidList.add(usersTask.getUsersid() + "");
						}
						
						usersTaskOrder.setUpdatetime(new Date());
						JSONObject resDBJSON = this.ordersService.updateOneUsersTaskOrderService(usersTaskOrder);
						if(Integer.valueOf(resDBJSON.get("code") + "") > 0)
						{
							ConstatFinalUtil.SYS_LOG.info(usersTaskOrder.getId() + ";" + usersTaskOrder.getStatusStr() + "--处理挂单更新信息--" + resDBJSON);
						}
					}else
					{
						ConstatFinalUtil.SYS_LOG.error(usersTaskOrder.getId() + ";" + usersTaskOrder.getStatusStr() + "--处理挂单更新信息--处理标志:" + cancelFlag);
					}
				}
				if(usersTaskOrderList.size() > 0 )
				{
					//更新收益
					operTaskOrderUpdatePrift(usersTask);
				}else
				{
					/* 下单交易,防止重复下单 */
					this.operTaskTradeService(usersTask);
				}
			}else if("second".equalsIgnoreCase(flag))
			{
				//更新收益
				operTaskOrderUpdatePrift(usersTask);
			}
		}
		
		//是否要查询余额的标志
		if(usersidList.size() > 0 )
		{
			//更新余额
			for (Iterator iterator = usersidList.iterator(); iterator.hasNext();) 
			{
				String usersid = (String) iterator.next();
				//更新用户的金额信息
				condMap.clear();
				condMap.put("id", usersid);
				condMap.put("extend", "true");
				if(ConstatFinalUtil.SYSPRO_MAP.get("users.balance.count") != null 
					&& ConstatFinalUtil.USERS_BALANCE_COUNT % Long.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("users.balance.count")) == 0 )
				{
					condMap.put("threadType", "wait");
				}
				AUsers users = this.usersService.findOneUsersService(condMap);
				ConstatFinalUtil.USERS_BALANCE_COUNT ++ ; 
			}
			//ConstatFinalUtil.INFO_MAP.put("usersBalance", "1");
		}else
		{
			//ConstatFinalUtil.INFO_MAP.put("usersBalance", "0");
		}
	}
	
	/**
	 * 买卖单同时进行
	 * @param dept
	 */
	public void operTaskTradeService(AUsersTask usersTask) 
	{
		//查询所有正在进行的任务
		//先交易
		//买单和卖单同时进行
		List<Callable<Object>> callList = new ArrayList<Callable<Object>>();
		//买单
		Map<String, Object> thrBuyMap = new HashMap<String, Object>();
		thrBuyMap.put("usersTask", usersTask);
		thrBuyMap.put("type", TradeEnum.TRADE_TYPE_BUY.getValue() + "");
		
		ServiceCallableUtil buyThreadUtil = new ServiceCallableUtil();
		buyThreadUtil.setParamsMap(thrBuyMap);
		buyThreadUtil.setOutTimerService(this);
		buyThreadUtil.setOperType("orderTrade");
		callList.add(buyThreadUtil);
		
		//卖单
		Map<String, Object> sellMap = new HashMap<String, Object>();
		sellMap.put("usersTask", usersTask);
		sellMap.put("type", TradeEnum.TRADE_TYPE_SELL.getValue() + "");
		
		ServiceCallableUtil sellThreadUtil = new ServiceCallableUtil();
		sellThreadUtil.setParamsMap(sellMap);
		sellThreadUtil.setOutTimerService(this);
		sellThreadUtil.setOperType("orderTrade");
		callList.add(sellThreadUtil);
		
		try {
			ExecutorServiceUtil.invokeAll(callList);
		} catch (InterruptedException e) {
			ConstatFinalUtil.SYS_LOG.error("同时下单操作异常了", e);
		}finally
		{
			ExecutorServiceUtil.shutdown();
		}
	}
	
	/**
	 * 更行任务的收益
	 * @param usersTask
	 * @return
	 */
	public boolean operTaskOrderUpdatePrift(AUsersTask usersTask)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		//每次都算一次收益
		double sellnum = 0 ;
		double buynum = 0 ; 
		double sellMoney = 0 ;
		double buyMoney = 0 ; 
		//统一算一遍收益
		double prift = 0 ;
		double fee = 0 ; 
		
		/* 只要有挂单,就停止计算收益 */
		condMap.clear();
		condMap.put("utid", usersTask.getId() + "");
		//只查询完成的订单
		condMap.put("status", AUsersTaskOrderEnum.STATUS_ORDERING.getStatus());
		List<AUsersTaskOrder> usersTaskOrderList = this.ordersService.findCondListUsersTaskOrderService(new PageInfoUtil(), condMap);
//		if(usersTaskOrderList.size() > 0 )
//		{
//			/* 说明有挂单 */
//			return false ; 
//		}
		
		//查询所有的未计算收益的子任务
		condMap.clear();
		condMap.put("utid", usersTask.getId() + "");
		//只查询完成的订单
		condMap.put("status", AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
		usersTaskOrderList = this.ordersService.findCondListUsersTaskOrderService(null, condMap);
		for (Iterator iterator2 = usersTaskOrderList.iterator(); iterator2
				.hasNext();)
		{
			AUsersTaskOrder usersOrder = (AUsersTaskOrder) iterator2
					.next();
			//完成的订单
			if(usersOrder.getOrdertype() == 0)
			{
				//买
				buynum += usersOrder.getTradeedval() ; 
				buyMoney += usersOrder.getTradeedval() * usersOrder.getPrice() ; 
			}else if(usersOrder.getOrdertype() == 1)
			{
				//卖
				sellnum += usersOrder.getTradeedval() ;
				sellMoney += usersOrder.getTradeedval() * usersOrder.getPrice() ;
			}
			
			/* 只有成交量大于0的时候,才统计收益 */
			if(usersOrder.getTradeedval() > 0)
			{
				fee += usersOrder.getFee() ; 
			}
			//usersOrder.setPriftstatus(Byte.valueOf("1"));
			usersOrder.setPriftstatus(AUsersTaskOrderEnum.PRIFTSTATUS_CALED.getStatus());
			
			/* 更新用户任务 */
			if(usersTask.getBuywbid() == 0 && usersOrder.getOrdertype() == AUsersTaskOrderEnum.ORDERTYPE_BUY.getStatus())
			{
				/* 买 */
				usersTask.setBuywbid( usersOrder.getUsersAccountObj().getWbid() );
			}else if(usersTask.getSellwbid() == 0 && usersOrder.getOrdertype() == AUsersTaskOrderEnum.ORDERTYPE_SELL.getStatus())
			{
				/* 卖 */
				usersTask.setSellwbid( usersOrder.getUsersAccountObj().getWbid() );
			}
			
			usersOrder.setUpdatetime(new Date());
			JSONObject resDBJSON = this.ordersService.updateOneUsersTaskOrderService(usersOrder);
			if(Integer.valueOf(resDBJSON.get("code") + "") > 0)
			{
				ConstatFinalUtil.SYS_LOG.info(usersOrder.getId() + ";" + usersOrder.getStatusStr() + "--子单计算收益更新信息--" + resDBJSON);
			}
		}
		
		//计算收益
		prift += sellMoney - buyMoney ;
		usersTask.setPrift(prift);
		usersTask.setBuynum(buynum);
		usersTask.setSellnum(sellnum);
		usersTask.setPriftfee(fee);
		
		//处理任务的状态
		double buynumTotal = this.doubleOperUtil.sub(usersTask.getBuynum(), usersTask.getFeenum()); 
		buynumTotal = doubleOperUtil.round(buynumTotal, 3, RoundingMode.DOWN.ordinal());
		double sellnumTotal = doubleOperUtil.round(usersTask.getSellnum(), 3, RoundingMode.DOWN.ordinal());
		if(usersTask.getSoutype() == AUsersTaskEnum.SOUTYPE_SYSTEM.getStatus()
			||
			usersTask.getSoutype() == AUsersTaskEnum.SOUTYPE_LONG.getStatus())
		{
			//系统创建
			//买卖相等,币永远不变,任务第一次价格>0,说明任务肯定可以终结
			if(Double.valueOf(buynumTotal).equals(Double.valueOf(sellnumTotal)))
			{
				if(usersTask.getPrift() > 0)
				{
					//说明有交易,并且挣到钱了
					//usersTask.setStatus(Byte.valueOf("3"));
					usersTask.setStatus(AUsersTaskEnum.STATUS_CALINCOME.getStatus());
				}else
				{
					//说明两个单都没有成,将设置为人工调整
					//usersTask.setStatus(Byte.valueOf("2"));
					usersTask.setStatus(AUsersTaskEnum.STATUS_MANUADJ.getStatus());
				}
				usersTask.setFinishtime(new Date());
			}else if(Double.valueOf(buynumTotal) - (Double.valueOf(sellnumTotal)) > 0 && usersTask.getSoutype() == AUsersTaskEnum.SOUTYPE_LONG.getStatus())
			{
				/*
				 * 买币>卖币,并且是长期搬砖,只要挣钱,就修改状态
				 * */
				if(usersTask.getPrift() > 0)
				{
					//说明有交易,并且挣到钱了
					//usersTask.setStatus(Byte.valueOf("3"));
					usersTask.setStatus(AUsersTaskEnum.STATUS_CALINCOME.getStatus());
					usersTask.setFinishtime(new Date());
				}
			}
		}else
		{
			//其它类型
			if(buynumTotal == usersTask.getTotalnum() && buynumTotal == usersTask.getSellnum())
			{
				if(usersTask.getPrift() > 0)
				{
					//说明有交易,并且挣到钱了
					//usersTask.setStatus(Byte.valueOf("3"));
					usersTask.setStatus(AUsersTaskEnum.STATUS_CALINCOME.getStatus());
				}else
				{
					//说明两个单都没有成,将设置为人工调整
					//usersTask.setStatus(Byte.valueOf("2"));
					usersTask.setStatus(AUsersTaskEnum.STATUS_MANUADJ.getStatus());
				}
				usersTask.setFinishtime(new Date());
			}
		}
		
		usersTask.setUpdatetime(new Date());
		JSONObject resDBJSON = this.ordersService.updateOneUsersTaskService(usersTask);
		if(Integer.valueOf(resDBJSON.get("code") + "") > 0 )
		{
			ConstatFinalUtil.SYS_LOG.info(usersTask.getStatusStr() + "---- 更新计算收益状态: ----" + resDBJSON + ",子订单的数量:" 
					+ usersTaskOrderList.size());
			/* 只要状态不等于进行中,就任务是成功 */
			if(usersTask.getStatus() != 1)
			{
				return true ; 
			}
		}
		
		/*
		//先处理买单
		boolean buyFlag = ordersBuyServiceUtil(usersTask);
		if(buyFlag)
		{
			//再处理卖单
			buyFlag = ordersSellServiceUtil(usersTask);
			if(usersTask.getBuynum() == 0)
			{
				//如果买单没有成功,任务直接完成,且不计算收益
				usersTask.setStatus(Byte.valueOf("2"));
			}
			//更新任务的买数量与卖数量
			usersTask.setUpdatetime(new Date());
			this.ordersService.updateOneUsersTaskService(usersTask);
		}
		*/
		return false ; 
	}

	/**
	 * 下单交易,买和卖同时下单
	 * @param usersTask 任务
	 * @param type 0:买,1:卖
	 */
	public void taskOrdersTradeService(AUsersTask usersTask , String type)
	{
		ConstatFinalUtil.SYS_LOG.info(type + "----- 准备下单 -----" + usersTask.getId());
		boolean upflag = false ; 
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		Map<String, String> paramsMap = new HashMap<String, String>();
		
		//下单返回的结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//下单成功就退出
		ITradeService tradeService = null;
		ATradeType tradeType = null ; 
		
		//下单,先买-----
		AUsersTaskOrder usersTaskOrder = new AUsersTaskOrder();
		usersTaskOrder.setUtid(usersTask.getId());
		
		usersTaskOrder.setTradeedval(0);
		String wbid = "" ; 
		String coinid = "" ; 
		if(type.equalsIgnoreCase(AUsersTaskOrderEnum.ORDERTYPE_BUY.getStatus() + ""))
		{
			//买
			double totalval = this.doubleOperUtil.sum(usersTask.getTotalnum(), usersTask.getFeenum());
			totalval = this.doubleOperUtil.sub(totalval, usersTask.getBuynum());
			usersTaskOrder.setTotalval(totalval);
			//ordersBtc.setTotalval(usersTask.getTotalnum() + usersTask.getFeenum() - usersTask.getBuynum());
			//设置网站卖的价格
			usersTaskOrder.setPrice(usersTask.getSellprice());
			usersTaskOrder.setSouprice(usersTask.getSousellprice());
			usersTaskOrder.setOrdertype(AUsersTaskOrderEnum.ORDERTYPE_BUY.getStatus());
			
			tradeService = TradeUtil.tradeServiceMap.get(usersTask.getSellwbid() + "") ; 
			
			wbid = usersTask.getSellwbid() + "";
			tradeType = usersTask.getSellTradeTypeObj() ; 
			coinid = tradeType.getTocoinid() + ""; 
			//设置交易类型
			usersTaskOrder.setCtid(tradeType.getId());
		}else if(type.equalsIgnoreCase(AUsersTaskOrderEnum.ORDERTYPE_SELL.getStatus() + ""))
		{
			//卖
			usersTaskOrder.setTotalval(usersTask.getTotalnum() - usersTask.getSellnum());
			//设置网站卖的价格
			usersTaskOrder.setPrice(usersTask.getBuyprice());
			usersTaskOrder.setSouprice(usersTask.getSoubuyprice());
			usersTaskOrder.setOrdertype(AUsersTaskOrderEnum.ORDERTYPE_SELL.getStatus());
			
			tradeService = TradeUtil.tradeServiceMap.get(usersTask.getBuywbid() + "") ;
			
			wbid = usersTask.getBuywbid() + "";
			tradeType = usersTask.getBuyTradeTypeObj() ; 
			coinid = tradeType.getFromcoinid() + ""; 
			//设置交易类型
			usersTaskOrder.setCtid(tradeType.getId());
		}
		
		//下单应该是交易的数量
		if(usersTask.getTotalnum() > usersTask.getDeptnum())
		{
			//交易的数量比剩余的数量还大
			usersTaskOrder.setTotalval(usersTask.getDeptnum());
		}
		
		/*usersTaskOrder.setStatus(Byte.valueOf("0"));
		usersTaskOrder.setPriftstatus(Byte.valueOf("0"));*/
		usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_UNSTART.getStatus());
		usersTaskOrder.setPriftstatus(AUsersTaskOrderEnum.PRIFTSTATUS_UNCALED.getStatus());
		
		usersTaskOrder.setCreatetime(new Date());
		usersTaskOrder.setUpdatetime(new Date());
		usersTaskOrder.setPubtime(new Date());
		
		//用户首次添加,还没有更新交易信息
		if(tradeType == null)
		{
			return  ; 
		}
		
		//如果买的交易数量为0;
		if(usersTaskOrder.getTotalval() <= 0)
		{
			return  ; 
		}
		
		//根据用户id和webid和交易类型查询uaid,多账户
		condMap.clear();
		condMap.put("wbid", wbid);
		condMap.put("usersid", usersTask.getUsersid() + "");
		//查询币种
		condMap.put("coinid", coinid + "");
		List<AUsersAccount> usersAccountList = this.usersService.findCondListUsersAccountService(null, condMap);
		for (Iterator iterator2 = usersAccountList.iterator(); iterator2
				.hasNext();)
		{
			AUsersAccount usersAccount = (AUsersAccount) iterator2.next();
			
			//验证余额
			if("1".equalsIgnoreCase(ConstatFinalUtil.SYSPRO_MAP.get("trade.auth.balance")))
			{
				if(usersTaskOrder.getOrdertype() == 0 && 
						usersAccount.getBalance() < usersTaskOrder.getSouprice() * usersTaskOrder.getTotalval())
				{
					//买币,
					resultMap.put("info", "买币余额不足:账户余额:" + usersAccount.getBalance() + ";花费金额:" + usersTaskOrder.getSouprice() * usersTaskOrder.getTotalval());
					continue ;
				}
				
				if(usersTaskOrder.getOrdertype() == 1 && 
						usersAccount.getBalance() < usersTaskOrder.getTotalval())
				{
					//卖币,
					resultMap.put("info", "卖币余额不足:账户余额:" + usersAccount.getBalance() + ";花费金额:" + usersTaskOrder.getTotalval());
					continue ;
				}
			}
			
			usersTaskOrder.setUaid(usersAccount.getId());
			//设置登陆认证
			tradeService.setAuthJSON(usersAccount.getAuthinfoJSON());
			
			paramsMap.clear();
			paramsMap.put("moneytype", tradeType.getName());
			paramsMap.put("type", type);
			paramsMap.put("price", usersTaskOrder.getSouprice()+ "");
			paramsMap.put("amount", usersTaskOrder.getTotalval() + "");
			
			int sleep = Integer.valueOf(ConstatFinalUtil.SYSPRO_MAP.get("orders.time")) ;
			resultMap = this.tradeOrdersService(tradeService, sleep ,
					paramsMap);
			if(resultMap.get("order_id") != null)
			{
				String ordersid = resultMap.get("order_id") + "" ; 
				usersTaskOrder.setOrdersn(ordersid);
				usersTaskOrder.setTradeedval(Double.valueOf(resultMap.get("deal_amount") + ""));
				//下单之后,全部是挂单
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERING.getStatus());
				upflag = true ; 
				break ; 
			}else
			{
				//下单失败
				ConstatFinalUtil.SYS_LOG.info("下单失败;任务id:" + usersTask.getId() + ";订单类型:"+ usersTaskOrder.getOrdertypeStr() +"--usersAccountid:"+ usersAccount.getId() 
						+ ";paramsMap:" + paramsMap + ";resultMap:" + resultMap);
			}
		}
		
		//更新下单情况
		if(upflag)
		{
			//计算交易手续费
			Map<String, Double> feeMap = this.removeFee(usersTaskOrder.getTradeedval(), usersTask);
			/*
			resultMap.put("sellfee", sellfee);
			resultMap.put("buyfee", buyfee);
			*/
			if(type.equalsIgnoreCase(AUsersTaskOrderEnum.ORDERTYPE_BUY.getStatus() + ""))
			{
				//买的交易量,已经完成的交易量
				usersTask.setBuynum(usersTask.getBuynum() + usersTaskOrder.getTradeedval());
				if(feeMap.get("sellfee") != null)
				{
					usersTaskOrder.setFee(feeMap.get("sellfee"));
				}
				
				//更新任务的买数量与卖数量
				usersTask.setUpdatetime(new Date());
				this.ordersService.updateBatchUsersTaskService("updateBuynum",usersTask);
			}else if(type.equalsIgnoreCase(AUsersTaskOrderEnum.ORDERTYPE_SELL.getStatus() + ""))
			{
				//卖的交易量,已经完成的交易量
				usersTask.setSellnum(usersTask.getSellnum() + usersTaskOrder.getTradeedval());
				if(feeMap.get("buyfee") != null)
				{
					usersTaskOrder.setFee(feeMap.get("buyfee"));
				}
				
				//更新任务的买数量与卖数量
				usersTask.setUpdatetime(new Date());
				this.ordersService.updateBatchUsersTaskService("updateSellnum",usersTask);
			}
			
			//更新买单信息
			usersTaskOrder.setTotalprice(usersTaskOrder.getPrice() * usersTaskOrder.getTradeedval());
			usersTaskOrder.setUpdatetime(new Date());
			JSONObject resDBJSON = this.ordersService.saveOneUsersTaskOrderService(usersTaskOrder);
			ConstatFinalUtil.SYS_LOG.info(usersTaskOrder.getOrdertypeStr() + "----- 处理订单完成;返回 -----" + resDBJSON);
		}else
		{
			ConstatFinalUtil.SYS_LOG.info("下单失败;任务id:" + usersTask.getId() + ";订单类型:"+ usersTaskOrder.getOrdertypeStr() 
					+ ";paramsMap:" + paramsMap + ";resultMap:" + resultMap + ";用户数量:" + usersAccountList.size());
		}
	}
	
	@Override
	public boolean cancelTaskOrdersService(AUsersTaskOrder usersTaskOrder)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		Map<String, String> paramsMap = new HashMap<String, String>();
		if(usersTaskOrder.getOrdersn() != null && !"".equalsIgnoreCase(usersTaskOrder.getOrdersn()) && !"null".equalsIgnoreCase(usersTaskOrder.getOrdersn()))
		{
			//查询用户账户
			condMap.clear();
			condMap.put("id", usersTaskOrder.getUaid() + "") ; 
			AUsersAccount usersAccount = this.usersService.findOneUsersAccountService(condMap);
			
			//查询交易的币种
			ATradeType tradeType = usersTaskOrder.getTradeTypeObj();
			if(tradeType == null)
			{
				condMap.clear();
				condMap.put("id", usersTaskOrder.getCtid() + "") ; 
				tradeType = this.websiteService.findOneTradeTypeService(condMap);
				if(tradeType == null)
				{
					//查询不到交易类型,直接返回false
					return false ; 
				}
			}
			
			String moneytype = tradeType.getName() ;
			
			ITradeService tradeService = TradeUtil.tradeServiceMap.get(usersAccount.getWbid() + "");
			tradeService.setAuthJSON(usersAccount.getAuthinfoJSON());
			paramsMap.clear();
			paramsMap.put("moneytype", moneytype);
			paramsMap.put("order_id", usersTaskOrder.getOrdersn() + "");
			paramsMap.put("amount", usersTaskOrder.getTotalval() + "");
			Map<String, Object> resultMap = this.cancelOrdersService(tradeService, paramsMap);
			if(resultMap.get("deal_amount") != null)
			{
				usersTaskOrder.setTradeedval(Double.valueOf(resultMap.get("deal_amount") + ""));
			}
			
			/* 只要交易网站撤单成功,系统就会把状态变为完成 */
			if("1".equalsIgnoreCase(resultMap.get("cancelFlag") + ""))
			{
				if(usersTaskOrder.getTradeedval() <= 0)
				{
					//订单未成交
					usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERKILL.getStatus());
				}else
				{
					//撤单成功
					usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
				}
			}else if("2".equalsIgnoreCase(resultMap.get("cancelFlag") + ""))
			{
				//撤单成功
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}else if("equals".equalsIgnoreCase(resultMap.get("cancelFlag") + ""))
			{
				/* 如果订单已经成交,强制将订单的总数量和成交量相等
				 * 因为有小数点精度的问题(交易网站) */
				usersTaskOrder.setTradeedval(usersTaskOrder.getTotalval());
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}else
			{
				//撤单失败,木有cancelFlag
				return false ; 
			}
			
			//完全成交
			if(usersTaskOrder.getTotalval() == usersTaskOrder.getTradeedval())
			{
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}
			return true ;
		}
		return false;
	}
	
	/**
	 * 部分成交也算订单完成状态
	 */
	@Override
	public boolean findTaskOrdersService(AUsersTaskOrder usersTaskOrder)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		Map<String, String> paramsMap = new HashMap<String, String>();
		if(usersTaskOrder.getOrdersn() != null && !"".equalsIgnoreCase(usersTaskOrder.getOrdersn()) 
				&& !"null".equalsIgnoreCase(usersTaskOrder.getOrdersn()))
		{
			//查询用户账户
			condMap.clear();
			condMap.put("id", usersTaskOrder.getUaid() + "") ; 
			AUsersAccount usersAccount = this.usersService.findOneUsersAccountService(condMap);
			
			//查询交易的币种
			ATradeType tradeType = usersTaskOrder.getTradeTypeObj();
			if(tradeType == null)
			{
				condMap.clear();
				condMap.put("id", usersTaskOrder.getCtid() + "") ; 
				tradeType = this.websiteService.findOneTradeTypeService(condMap);
				if(tradeType == null)
				{
					//查询不到交易类型,直接返回false
					return false ; 
				}
			}
			
			String moneytype = tradeType.getName() ;
			
			ITradeService tradeService = TradeUtil.tradeServiceMap.get(usersAccount.getWbid() + "");
			tradeService.setAuthJSON(usersAccount.getAuthinfoJSON());
			paramsMap.clear();
			paramsMap.put("moneytype", moneytype);
			paramsMap.put("order_id", usersTaskOrder.getOrdersn() + "");
			paramsMap.put("amount", usersTaskOrder.getTotalval() + "");
			Map<String, Object> resultMap = this.findOrdersSingle(tradeService, paramsMap);
			if(resultMap.get("deal_amount") != null)
			{
				usersTaskOrder.setTradeedval(Double.valueOf(resultMap.get("deal_amount") + ""));
			}
			/* 处理一下订单的真实成交价格 */
			if(resultMap.get("tradePrice") != null)
			{
				usersTaskOrder.setTradePrice(Double.valueOf(resultMap.get("tradePrice") + ""));
			}
			
			/**
			 * 订单的状态为完成,并且交易网站中的订单已经为撤销
			 */
			if("2".equalsIgnoreCase(resultMap.get("cancelFlag") + ""))
			{
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}else if("equals".equalsIgnoreCase(resultMap.get("cancelFlag") + ""))
			{
				/* 如果订单已经成交,强制将订单的总数量和成交量相等
				 * 因为有小数点精度的问题(交易网站) */
				usersTaskOrder.setTradeedval(usersTaskOrder.getTotalval());
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}else
			{
				//撤单失败,木有cancelFlag
				return false ; 
			}
			
			//完全成交
			if(usersTaskOrder.getTotalval() == usersTaskOrder.getTradeedval())
			{
				usersTaskOrder.setStatus(AUsersTaskOrderEnum.STATUS_ORDERFINISH.getStatus());
			}
			return true ;
		}
		return false;
	}
	
	/**
	 * 下单操作
	 * 
	 * 返回以下几个属性
	 * @param	参数:
	 * moneytype:交易类型
	 * type:0买,1卖
	 * price:价格
	 * amount:金额
	 * 
	 * @return
	 * order_id:订单id,
	 * deal_amount:订单成交量
	 * cancelFlag:订单是否撤单
	 */
	public Map<String, Object> tradeOrdersService(ITradeService tradeService , int sleep , Map<String, String> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		
		String moneytype = condMap.get("moneytype") + ""; 
		String type = condMap.get("type") + "" ;
		//必须返回的参数
		resultMap.put("deal_amount", "0");
		try
		{
			//都保留3位小数
			double price = doubleOperUtil.round(Double.valueOf(condMap.get("price") + ""), 3, RoundingMode.DOWN.ordinal());
			double amount = doubleOperUtil.round(Double.valueOf(condMap.get("amount") + ""), 3, RoundingMode.DOWN.ordinal());
			
			//下单成功就退出
			paramsMap.put("moneytype", moneytype);
			paramsMap.put("type", type );
			paramsMap.put("price", price + "");
			paramsMap.put("amount", amount + "");
			//返回的有订单id
			JSONObject responseJSON = tradeService.trade(paramsMap);
			if("0".equalsIgnoreCase(responseJSON.get("code") + ""))
			{
				//下单成功
				JSONObject dataJSON = (JSONObject) responseJSON.get("data");
				//存储订单id
				resultMap.put("order_id", dataJSON.get("order_id") + "");
				if("1".equalsIgnoreCase(paramsMap.get("type")))
				{
					ConstatFinalUtil.SYS_LOG.info(paramsMap + "----- 卖单 下单成功 -----" + dataJSON);
				}else if("0".equalsIgnoreCase(paramsMap.get("type")))
				{
					ConstatFinalUtil.SYS_LOG.info(paramsMap + "----- 买单 下单成功 -----" + dataJSON);
				}
				//下单成功后的所有操作都认为是挂单
				resultMap.put("cancelFlag", "0");
			}
		}catch(Exception e)
		{
			ConstatFinalUtil.SYS_LOG.error("下单报错了,得重视;参数:" + condMap + ";返回值:" + resultMap , e);
		}
		return resultMap;
	}
	
	/**
	 * 取消挂单
	 * 下单操作
	 * 
	 * 返回以下几个属性
	 * @param	参数:
	 * moneytype:交易类型
	 * order_id:订单id,
	 * amount:订单的交易量
	 * 
	 * @return
	 * deal_amount:订单成交量
	 * cancelFlag:订单是否撤单
	 * 		2:(equals):订单成交量和订单的总量一致;已成交;
	 * 		1:订单撤单成功
	 */
	public Map<String, Object> cancelOrdersService(ITradeService tradeService , Map<String, String> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		
		boolean ordersflag = true ; 
		String orderid = condMap.get("order_id") + "" ; 
		//返回的有订单id,查询未完成的挂单
		paramsMap.put("moneytype", condMap.get("moneytype") + "");
		/* 查询所有的挂单 */
		paramsMap.put("order_id", "-1");
		JSONObject responseJSON = tradeService.getOrders(paramsMap);
		if("0".equalsIgnoreCase(responseJSON.get("code") + ""))
		{
			JSONObject dataJSON = (JSONObject) responseJSON.get("data");
			JSONArray ordersArr = (JSONArray) dataJSON.get("ordersList");
			if(ordersArr.size() > 0 )
			{
				//说明订单没有成交,还在挂单中
				for (Iterator iterator3 = ordersArr.iterator(); iterator3
						.hasNext();)
				{
					JSONObject ordersJSON = (JSONObject) iterator3.next();
					if(orderid.equalsIgnoreCase(ordersJSON.get("order_id") + ""))
					{
						ordersflag = false ;
						//已成交量
						resultMap.put("deal_amount", ordersJSON.get("deal_amount") + "");
						//撤销订单
						paramsMap.clear();
						paramsMap.put("moneytype", condMap.get("moneytype"));
						paramsMap.put("order_id", orderid);
						responseJSON = tradeService.cancelOrder(paramsMap);
						if("0".equalsIgnoreCase(responseJSON.get("code") + ""))
						{
							dataJSON = (JSONObject) responseJSON.get("data");
							if(orderid.equalsIgnoreCase(dataJSON.get("order_id") + ""))
							{
								//订单取消成功
								resultMap.put("cancelFlag", "1");
								break ; 
							}
						}
					}
				}
			}
		}
		
		/* 获取不到挂单的状态
		 * 查询订单详情,肯定是订单完成的状态
		 *  */
		if(ordersflag)
		{
			/* 查询订单的详情 */
			Map<String, Object> ordersResMap = this.findOrdersSingle(tradeService, condMap);
			resultMap.putAll(ordersResMap);
		}
		return resultMap ;
	}
	
	/**
	 * 查询订单的状态
	 * @param tradeService	处理订单的接口
	 * 		order_id:订单id;
	 * 		moneytype:交易类型
	 * @param condMap	orderid:订单id
	 * @return
	 * cancelFlag:
	 * 	2:订单成交量和订单的总量一致;已成交;
	 * deal_amount:订单成交量
	 * tradePrice:订单的成交价格
	 * equals:强制修改为订单量和成交量一致
	 */
	public Map<String, Object> findOrdersSingle(ITradeService tradeService , Map<String, String> condMap)
	{
		/*
		 * 存储结果
		 */
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 默认值 */
		resultMap.put("deal_amount", "0");
		
		/* 存储参数 */
		Map<String, String> paramsMap = new HashMap<String, String>();
		/* 获取订单的id */
		String orderid = condMap.get("order_id");
		/* 不管有木有撤销订单,都要对订单做一些标识 */
		/* 获取不到挂单的状态 */
		/* 查询不到挂单;有可能成交了,有可能撤单成功了
		 * 所以需要再查询一下订单的详情 */
		paramsMap.clear();
		paramsMap.put("moneytype", condMap.get("moneytype") + "");
		paramsMap.put("order_id",orderid);
		JSONObject resultJSON = tradeService.getOrdersSingle(paramsMap);
		/* 存储查看订单信息的结果 */
		resultMap.put("resultJSON", resultJSON);
		if("0".equalsIgnoreCase(resultJSON.get("code") + ""))
		{
			JSONObject dataJSON = (JSONObject) resultJSON.get("data");
			if(dataJSON != null)
			{
				//处理结果
				JSONObject ordersJSON = (JSONObject) dataJSON.get("orders");
				if(ordersJSON != null)
				{
					/* 将数字按照小数位,做处理
					 *  */
					/*String deal_amountStr = this.regexUtil.parseDouble(Double.valueOf(ordersJSON.get("deal_amount") + ""), 3) ; 
					Double deal_amount = Double.valueOf(deal_amountStr);*/
					//订单完全成交
					resultMap.put("deal_amount", ordersJSON.get("deal_amount") + "");
					/* 真实的成交价格 */
					resultMap.put("tradePrice", ordersJSON.get("avg_price"));
					
					if((TradeEnum.TRADE_STATUS_CANCEL.getValue() + "").equalsIgnoreCase(ordersJSON.get("status") + ""))
					{
						/*已经撤单成功*/
						resultMap.put("cancelFlag", "2");
					}else if((TradeEnum.TRADE_STATUS_DEALED.getValue() + "").equalsIgnoreCase(ordersJSON.get("status") + ""))
					{
						/*订单已经成交*/
						resultMap.put("cancelFlag", "equals");
					}
					
					/* 如果此订单的下单量和成交相量相等,那肯定是已经成效了 */
					if((ordersJSON.get("deal_amount") + "").equals(ordersJSON.get("amount")))
					{
						/*成交量和总数量相等时,肯定已经成交*/
						resultMap.put("cancelFlag", "equals");
					}
				}
			}
		}
		return resultMap ; 
	}
}
